import React, { useEffect, useState } from 'react';

function ajaxTest() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(
        new Array(20).fill(1).map((_d, i) => {
          return { id: i };
        })
      );
    }, 1000);
  });
}

export default function Demo() {
  const [list, setList] = useState(false);

  useEffectAbort(() => {
    ajaxTest().then(res => {
      setList(res);
    });
  }, []);

  return (
    <ListStatus data={list}>
      <ul>
        {list.map((d, i) => {
          return <div key={d.id}>{d.id}</div>;
        })}
      </ul>
    </ListStatus>
  );
}

function useEffectAbort(serverFun, arr = []) {
  useEffect(() => {
    serverFun();
    return () => {
      serverFun.abort();
    };
  }, [...arr]);
  return null;
}

function ListStatus({ data, loading, empty, children }) {
  if (!loading) {
    loading = <span>loading...</span>;
  }
  if (!empty) {
    empty = <span>Empty</span>;
  }
  if (data === false) {
    return loading;
  }
  if (data && data.length === 0) {
    return empty;
  }
  if (data && data.length > 0) {
    return children;
  }
  return <div>error</div>;
}
